import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { Form, Button, Row, Col } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import Loader from "../components/Loader";
import Message from "../components/Message";
import { getUserDetails, adminUpdateUser } from "../actions/userActions";
import FormContainer from "../components/FormContainer";
import { USER_ADMIN_UPDATE_RESET } from "../constants/userConstants";

const UserEditScreen = ({ match, history }) => {
  const userId = match.params.id;

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [isAdmin, setIsAdmin] = useState(false);

  const dispatch = useDispatch();

  //获取用户信息
  const userDetails = useSelector((state) => state.userDetails);
  const { loading, error, user } = userDetails;
  //获取返回的状态
  const adminUpdate = useSelector((state) => state.adminUpdate);
  const {
    loading: loadingUpdate,
    error: errorUpdate,
    success: successUpdate,
  } = adminUpdate;

  useEffect(() => {
    if (successUpdate) {
      dispatch({ type: USER_ADMIN_UPDATE_RESET });
      history.push("/admin/userlist");
    } else {
      if (!user.name || user._id != userId) {
        dispatch(getUserDetails(userId));
      } else {
        setName(user.name);
        setEmail(user.email);
        setIsAdmin(user.isAdmin);
      }
    }
  }, [dispatch, history, user, userId, successUpdate]);

  //表单提交
  const submitHandler = (e) => {
    e.preventDefault();
    dispatch(adminUpdateUser({ _id: userId, name, email, isAdmin }));
  };

  return (
    <FormContainer>
      <Link to="/admin/userlist" className="btn btn-dark my-3 py-1">
        返回上一页
      </Link>
      <h1>编辑用户界面</h1>
      {loadingUpdate && <Loader></Loader>}
      {errorUpdate && <Message variant="danger">{errorUpdate}</Message>}
      {loading ? (
        <Loader></Loader>
      ) : error ? (
        <Message variant="danger"></Message>
      ) : (
        <Form onSubmit={submitHandler}>
          <Form.Group controlId="name">
            <Form.Label>用户名：</Form.Label>
            <Form.Control
              type="text"
              placeholder="请输入用户名"
              value={name}
              onChange={(e) => setName(e.target.value)}
            ></Form.Control>
          </Form.Group>
          <Form.Group controlId="email">
            <Form.Label>邮箱地址：</Form.Label>
            <Form.Control
              type="email"
              placeholder="请输入邮箱"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            ></Form.Control>
          </Form.Group>
          <Form.Group controlId="isAdmin">
            <Form.Check
              type="checkbox"
              label="Is Admin"
              checked={isAdmin}
              onChange={(e) => setIsAdmin(e.target.checked)}
            ></Form.Check>
          </Form.Group>
          <Button type="submit" className="py-1" variant="primary">
            更新信息
          </Button>
        </Form>
      )}
    </FormContainer>
  );
};

export default UserEditScreen;
